package com.morrislabs.graph
{
	import com.adobe.flex.extras.controls.springgraph.Item;
	import com.adobe.flex.extras.controls.springgraph.Graph;
			
	public class GraphBuilder
	{
		public function GraphBuilder()
		{
		}

		/** loads a XML document into a Graph. We only use the <friend> and <relation> tags,
		and ignore all the other information and tags in the XML. */
		public static function loadXML(xml: XML, g: Graph): void {
			var gid: String = xml.@id;
			var item: Item;
			
			// look for <friend> elements that have no namespace
			for each (var node: XML in xml..friend) {
				item = new Item(gid + node.@id);
				item.data = node;
				g.add(item);
			}
			
			
			// look for <relation> elements that have no namespace
			for each (var relation: XML in xml..relation) {
				loadRelation(relation, g, gid);
			}
			

		}
		
		/** load a relation into a graph. A relation looks like this
		 *   <relation id="b6" fromID="a1" toID="a3" order="1"/>
 		 */
		private static function loadRelation(relation: XML, g: Graph, gid: String): void {
			var fromID: String;
			var toID: String;
			var bond: Number;

				fromID = relation.@fromID;
				toID = relation.@toID;
				bond = relation.@bond;

			
			// find the 2 friends, based on their id's
			var fromItem: Item = g.find(gid + fromID);
			var toItem: Item = g.find(gid + toID);
			
			if((fromItem != null) && (toItem != null)) {
				// get the 'bond' level of the relation.
				
				if(bond < 0) bond = 0;
				if(bond > 10) bond = 10;
				
				// create the data object that is associated with this edge.
				// this object must specify various visual parameters for the line
				// that represents the relation. (note: its ok to omit this, in
				// which case the edge will be drawn using default settings).
				var data: Object = {settings: {alpha: 0.5, color: 0, thickness: (bond * 3) - 2}};
				
				// add the relation (a.k.a. link) to the graph
				g.link(fromItem, toItem, data);
			}
			
		}
	}
}